import { getToken, setToken, removeToken, setTimeStamp } from '@/utils/auth'
import { login, getUserInfo, getUserDetailById } from '@/api/user'

export default {
  namespaced: true,
  // 状态
  state: {
    token: getToken(),
    userInfo: {}
  },
  // 修改状态
  mutations: {
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    removeToken(state) {
      state.token = null
      removeToken()
    },
    setUserInfo(state, info) {
      state.userInfo = { ...info }
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  // 执行异步
  actions: {
    async login({ commit }, userInfo) {
      const token = await login(userInfo)
      commit('setToken', token)
      setTimeStamp()
    },
    async getUserInfo({ commit }) {
      const result = await getUserInfo()
      const baseInfo = await getUserDetailById(result.userId)
      const baseResult = { ...result, ...baseInfo }
      commit('setUserInfo', baseResult)
      return baseResult
    },
    logout({ commit }) {
      commit('removeToken')
      commit('removeUserInfo')
    }
  }
}
